import yaml

def open_jsonref(fileUrl):
    import jsonref
    import requests
    if fileUrl[0:4] == "http":
        # es URL
        pointer = requests.get(fileUrl)
        return jsonref.loads(pointer.content.decode('utf-8'))
    else:
        # es file
        file = open(fileUrl, "r")
        return jsonref.loads(file.read())


def open_json(fileUrl):
    import json
    import requests
    if fileUrl[0:4] == "http":
        # es URL
        pointer = requests.get(fileUrl)
        return json.loads(pointer.content.decode('utf-8'))
    else:
        # es file
        file = open(fileUrl, "r")
        return json.loads(file.read())


def echo(concept, variable):
    print("*** " + concept + " ***")
    print(variable)
    print("--- " + concept + " ---")


def read_yaml(fileUrl):
    import yaml
    import requests
    if fileUrl[0:4] == "http":
        # es URL
        pointer = requests.get(fileUrl)
        return yaml.safe_load(pointer.content.decode('utf-8'))
    else:
        # es file
        with open(fileUrl) as f:
            try:
                dict = yaml.load(f, Loader=yaml.SafeLoader)
                return dict
            except yaml.YAMLError as e:
                print(e)


def data_models():

    import os

    config = open_jsonref("config.json")
    dbtype_list = os.listdir(".")
    dataModels = []

    for dbtype in dbtype_list:
        if not (os.path.isfile(os.path.join(".", dbtype))) and (dbtype not in config["ignore_directory"]):
            dataModels.append(dbtype)

    return dataModels


# parser = argparse.ArgumentParser(description='')
# parser.add_argument('--name', dest='name', type=str)
# args = parser.parse_args()
# dataModel = args.name

dataModels = data_models()

tab = "  "
nl = chr(10)
rootModelUrl = "https://gitee.com/dzgrief/data-model/raw/master/"
swaggerHeader = """---"""
swaggerBody = """paths: 
  /ngsi-ld/v1/entities: 
    get: 
      description: "Retrieve a set of entities which matches a specific query from an NGSI-LD system"
      parameters: 
        - 
          in: query
          name: type
          required: true
          schema: 
            enum: 
              - Building
            type: string
      responses: 
        ? "200"
        : 
          content: 
            application/ld+json: 
              examples: 
                keyvalues: 
                  summary: "Key-Values Pairs"
                  value: 
                    - 
                      $ref: "https://gitee.com/dzgrief/data-model/raw/master/Building/examples/example.json"
                normalized: 
                  summary: "Normalized NGSI-LD"
                  value: 
                    - 
                      $ref: "https://gitee.com/dzgrief/data-model/raw/master/Building/examples/example-normalized.jsonld"
          description: OK
      tags: 
        - ngsi-ld
tags: 
  - 
    description: "NGSI-LD Linked-data Format"
    name: ngsi-ld"""


for dataModel in dataModels:

    outputFile = "./" + dataModel + "/swagger.yaml"
    modelYaml = "./" + dataModel + "/model.yaml"

    try:
        modelContent = read_yaml(modelYaml)
        modelPresent = True
        modelDict = modelContent[dataModel]
    except:
        modelPresent = False

    if modelPresent:
        swaggerContent = swaggerHeader + nl
        # swaggerContent = nl
        # swaggerContent += nl
        swaggerContent += "components:" + nl
        swaggerContent += 1 * tab + "schemas: " + nl
        swaggerContent += 2 * tab + dataModel + ": " + nl
        swaggerContent += 3 * tab + "$ref: " + chr(34) + rootModelUrl + dataModel + "/model.yaml" + "#/" + dataModel + chr(34) + nl
        swaggerContent += "info:" + nl
        swaggerContent += 1 * tab + "description:  " + chr(34) + dataModel + " Definitions from Data Models" + chr(34) + nl
        if "description" in modelDict:
            swaggerContent += 2 * tab + modelDict["description"] + nl
        swaggerContent += 1 * tab + "title: " + dataModel + nl
        swaggerContent += 1 * tab + "version: " + chr(34) + modelDict["x-version"] + chr(34) + nl
        swaggerContent += "openapi: " + chr(34) + "3.0.0" + chr(34) + nl
        swaggerContent += nl
        customBody = swaggerBody.replace("- Building", "- " + dataModel).replace("/raw/master/Building/", "/raw/master/" + dataModel + "/")

        for line in customBody.splitlines():
            swaggerContent += line + nl

        # print(swaggerContent)

        with open(outputFile, "w") as output:
           output.write(swaggerContent)
